package com.leessy.r229.utils;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.util.Log;

import androidx.core.content.ContextCompat;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class InstallSessionUtil2 {
    private static final String TAG = "InstallSessionUtil";
    Context ddddd;
    String packgeAdd = "";

    public void installApps() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.PACKAGE_ADDED");
        intentFilter.addAction("com.android.installApk");
        intentFilter.setPriority(1000);
        intentFilter.addDataScheme("package");
        BroadcastReceiver appStateChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null && "android.intent.action.PACKAGE_ADDED".equals(intent.getAction())) {
                    String dataString = "" + intent.getDataString();
                    dataString = dataString.replace("package:", "");
                    Log.d(TAG, "onReceive: dataString=" + dataString);
                    Log.d(TAG, "onReceive: getAction=" + intent.getAction());
                    if (dataString.equals(packgeAdd)) {
                        packgeAdd = "";//避免重复
                        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packgeAdd);
                        if (launchIntent != null) {
                            context.startActivity(launchIntent);
                        } else {
                            Log.d(TAG, "start: no app");// 目标应用程序未安装
                        }

                    }
                } else if (intent != null && "com.android.installApk".equals(intent.getAction())) {
                    Log.d(TAG, "onReceive: " + intent.getAction());
                    String fileName = intent.getStringExtra("fileName");
                    String packgeName = intent.getStringExtra("packageName");
                    packgeAdd = packgeName;
                    runInstallSession(fileName, ddddd);
                }
            }
        };
        ddddd.registerReceiver(appStateChangeReceiver, intentFilter);
    }


    public static void runInstallSession(String apkSource, Context context) {
        PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        InputStream is = null;
        OutputStream os = null;
        boolean succeed = false;

        try {
            Log.d(TAG, "runInstallSession start");
            PackageManager pm = context.getPackageManager();
            PackageInstaller packageInstaller = pm.getPackageInstaller();

            PackageInfo info = pm.getPackageArchiveInfo(apkSource, PackageManager.GET_ACTIVITIES);
            Log.d(TAG, "runInstallSession packageName=" + info.packageName);
            params.setAppPackageName(info.packageName);

            int sessionId = packageInstaller.createSession(params);
            byte[] buffer = new byte[65536];
            PackageInstaller.Session session = packageInstaller.openSession(sessionId);
            is = new FileInputStream(apkSource);
            long sizeBytes = apkSource.length();
            Log.d(TAG, "runInstallSession sizeBytes=" + String.valueOf(sizeBytes));
            os = session.openWrite("PackageInstaller", 0, sizeBytes);
            int c = 0;
            while ((c = is.read(buffer)) != -1) {
                os.write(buffer, 0, c);
            }
            session.fsync(os);
            os.close();
            os = null;
            Intent intent = new Intent("com.android.preinstall");
            intent.putExtra("pkgname", info.packageName);
            int index = info.packageName.hashCode();
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, index, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
            session.commit(pendingIntent.getIntentSender());
            succeed = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d(TAG, "runInstallSession " + (succeed ? "success" : "failed"));
        }
    }

}
